package game

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"sync"
	"time"
)

var manageMailEngine *MailEngine

type Mail struct {
	MailID int64
	ReceiveId int64
	MailTitle string
	MailText string
}

type MailEngine struct {
	UserMailMap map[int64][]*Mail	//userid为key，该userid对应的所有mail为slice
	CurMailID 	int64

	setMailChannel chan *Mail
	mailIDMutex sync.Mutex
	getUserMailMutex sync.Mutex
	msgChannel  chan int
	path   string
}

func GetMailEngine() *MailEngine {
	if manageMailEngine == nil {
		manageMailEngine = new(MailEngine)
		manageMailEngine.UserMailMap = make(map[int64][]*Mail)
		manageMailEngine.setMailChannel = make(chan *Mail)
		manageMailEngine.msgChannel = make(chan int)

		manageMailEngine.InitData()
		manageMailEngine.LoadData()
	}
	return manageMailEngine
}

func (self *MailEngine) AddCurMailID() (CurMailID int64){
	self.mailIDMutex.Lock()
	defer self.mailIDMutex.Unlock()
	self.CurMailID = self.CurMailID + 1
	return self.CurMailID
}

func (self *MailEngine) Run() {
	GetServer().AddGo()
	//每10秒保存一次
	ticker := time.NewTicker(time.Second * 1)
	for {
		select {
		case <-ticker.C:
			if time.Now().Unix()%10 == 0 {
				//保存数据
				self.SaveData()
			}
		case mail,ok:=<-self.setMailChannel:
			if ok{
				if self.UserMailMap != nil {
					mailSlice := self.UserMailMap[mail.ReceiveId]
					if mailSlice == nil {
						self.UserMailMap[mail.ReceiveId] = []*Mail{mail}
					} else {
						self.UserMailMap[mail.ReceiveId] = append(mailSlice, mail)
					}
				}
			}
		case _,ok:=<-self.msgChannel:
			if !ok{
				close(self.setMailChannel)
				GetServer().GoDone()
				return
			}
		}
	}
}

func (self *MailEngine) SendMailToChannel(AMail *Mail) {
	self.setMailChannel <- AMail
}

func (self *MailEngine) GetUserMail(AUserId int64) ([]*Mail) {
	self.getUserMailMutex.Lock()
	defer self.getUserMailMutex.Unlock()

	if self.UserMailMap != nil {
		UserMailSlice := self.UserMailMap[AUserId]
		delete(self.UserMailMap, AUserId)
		return UserMailSlice
	} else {
		return nil
	}
}

func (self *MailEngine) Close() {
	close(self.msgChannel)
}

func (self *MailEngine) LoadData() {
	configFile, err := ioutil.ReadFile(self.path)
	if err != nil {
		self.InitData()
		return
	}
	err = json.Unmarshal(configFile, &self)
	if err != nil {
		self.InitData()
		return
	}

	return
}

func (self *MailEngine) SaveData() {
	content, err := json.Marshal(self)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(self.path, content, os.ModePerm)
	if err != nil {
		return
	}
}

func (self *MailEngine) InitData() {
	path := GetServer().Config.LocalSavePath
	savePath := path + fmt.Sprintf("/Mail")
	self.path = savePath + fmt.Sprintf("/Mail.json")
	_, err := os.Stat(savePath)
	if err != nil {
		err = os.Mkdir(savePath, os.ModePerm)
		if err != nil {
			return
		}
	}
}